<template>
  <el-card class="box">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      label-width="100px"
      v-show="!isRegister"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          placeholder="密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="btn"
          type="primary"
          @click="submitForm('loginForm', 'login')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>

    <el-form
      ref="registerForm"
      :model="registerForm"
      :rules="registerRules"
      label-width="100px"
      v-show="isRegister"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="registerForm.password"
          placeholder="密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="registerForm.mobile"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="btn"
          type="primary"
          @click="submitForm('registerForm', 'register')"
          >注册</el-button
        >
      </el-form-item>
    </el-form>

    <el-button @click="toggleForm"
      >切换到{{ isRegister ? '登录' : '注册' }}</el-button
    >
  </el-card>
</template>

<script>
import { reactive } from 'vue'
import { ElForm, ElInput, ElButton, ElCard, ElMessage } from 'element-plus'

import axiosUtil from '@/net/axiosUtil' // 引入封装的 axios
import router from '@/router' // 引入路由配置

export default {
  components: {
    ElForm,
    ElInput,
    ElButton,
    ElCard
  },
  data () {
    return {
      isRegister: false, // 控制显示登录表单还是注册表单
      loginForm: reactive({ username: '', password: '' }),
      registerForm: reactive({
        username: '',
        password: '',
        mobile: ''
      }),
      loginRules: reactive({
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }),
      registerRules: reactive({
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
        ]
      })
    }
  },
  methods: {
    toggleForm () {
      this.isRegister = !this.isRegister
      this.$refs['loginForm'].resetFields()
      this.$refs['registerForm'].resetFields()
    },
    submitForm (formRef, actionType) {
      this.$refs[formRef].validate(valid => {
        if (valid) {
          if (actionType === 'login') {
            this.loginUser()
          } else if (actionType === 'register') {
            this.registerUser()
          }
        }
      })
    },

    async registerUser () {
      try {
        const response = await axiosUtil.post(
          '/api/v1/users/register',
          this.registerForm
        )
        // 处理成功的逻辑
        console.log('注册成功：', response.data)
        ElMessage.success(response.data.msg)
      } catch (error) {
        // 处理失败的逻辑
        console.error('注册失败：', error.response.data)
        ElMessage.error(error.response.data.msg)
      }
    },
    async loginUser () {
      try {
        // 使用表单编码的方式提交数据
        const params = new URLSearchParams(this.loginForm).toString()

        const response = await axiosUtil.post('/api/v1/auth/login', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded' // 设置请求头
          }
        })
        // 处理成功的逻辑
        console.log('登录成功：', response)
        if (response.data.code === '00000') {
          localStorage.setItem('token', response.data.data.accessToken)
          router.push({ name: 'Home' })
        }
      } catch (error) {
        // 处理失败的逻辑
        console.error('登录失败：', error)
      }
    }
  }
}
</script>

<style scoped>
.box {
  width: 400px;
  margin: 100px auto;
}

.btn {
  display: flex;

  margin: auto;
}
</style>
